<template>
  <base-breadcrumb class="newsManage-container">
    <searchData :search-data="searchArr" :need-filter-empty-val="false" @search="handleSearch" />
    <a-card :bordered="false">
      <!-- <title-name title="新闻列表" /> -->
      <div class="pub-table-action-btn mb12">
        <a-button icon="plus" v-btnPermission="'pa_017_add_01'" type="primary" @click="handleUpdate({}, 'add')"
          >新增新闻</a-button
        >
      </div>
      <div class="pub-table-select-count mb10">
        <a-icon type="info-circle" theme="twoTone" />
        <span>
          共计：
          <a>{{ totalInfo.totalNum || 0 }} 个</a>
        </span>
      </div>
      <list-table
        ref="table"
        row-key="id"
        :columns="columns"
        :request="loadData"
        show-size-changer
        show-quick-jumper
        show-pagination="auto"
      >
        <template slot="type" slot-scope="text">
          {{ filterLabel(text, 'type') }}
        </template>
        <template slot="sources" slot-scope="text">
          {{ filterLabel(text, 'sources') }}
        </template>
        <template slot="topStatus" slot-scope="text">
          {{ filterLabel(text, 'topStatus') }}
        </template>
        <template slot="releaseStatus" slot-scope="text">
          {{ filterLabel(text, 'releaseStatus') }}
        </template>
        <template slot="action" slot-scope="text, record">
          <MoreButton>
            <a v-btnPermission="'pa_017_loo_04'" @click="handleUpdate(record, 'look')">查看</a>
            <a v-btnPermission="'pa_017_lipub_02'" @click="handleUpdate(record, 'publish')">发布</a>
                <a
                  v-btnPermission="'pa_017_cel_06'"
                  v-if="checkMoreBtnVisible(record).isRevoke"
                  @click="handleUpdate(record, 'revoke')"
                >
                  撤销
                </a>
                <a
                  v-btnPermission="'pa_017_top_07'"
                  v-if="checkMoreBtnVisible(record).isSetTop"
                  @click="handleUpdate(record, 'setTop')"
                >
                  置顶
                </a>
                <a
                  v-btnPermission="'pa_017_top_07'"
                  v-if="checkMoreBtnVisible(record).isCancelTop"
                  @click="handleUpdate(record, 'cancelTop')"
                >
                  取消置顶
                </a>
                <a
                  v-btnPermission="'pa_017_del_03'"
                  v-if="checkMoreBtnVisible(record).isDelete"
                  @click="handleUpdate(record, 'delete')"
                >
                  删除
                </a>
          </MoreButton>
        </template>
      </list-table>
    </a-card>
  </base-breadcrumb>
</template>

<script>
import {
  getList,
  getNoReleaseNewsNum,
  updateTopStatus,
  updateReleaseStatus,
  undoNews,
  deleteData,
  getContentById
} from '@/api/partyMasses/partyManage/newsManage.js'
import { NEWS_TYPE, NEWS_SOURCE, TOP_STATUS, RELEASE_STATUS } from './model'

const searchArr = [
  {
    name: '新闻标题',
    value: 'title',
    type: 'input'
  },
  {
    name: '发布时间',
    value: 'releaseTime',
    type: 'dateRange',
    attr: {
      rangeFormat: ['releaseStartTime', 'releaseEndTime']
    }
  },
  {
    name: '发布状态',
    value: 'releaseStatus',
    type: 'select',
    data: Object.keys(RELEASE_STATUS).map((key) => {
      return {
        label: RELEASE_STATUS[key],
        value: key
      }
    })
  },
  {
    name: '置顶状态',
    value: 'topStatus',
    type: 'select',
    data: Object.keys(TOP_STATUS).map((key) => {
      return {
        label: TOP_STATUS[key],
        value: key
      }
    })
  },
  {
    name: '创建时间',
    value: 'createTime',
    type: 'dateRange',
    attr: {
      rangeFormat: ['createStartTime', 'createEndTime']
    }
  },
  {
    name: '新闻类别',
    value: 'type',
    type: 'select',
    data: Object.keys(NEWS_TYPE).map((key) => {
      return {
        label: NEWS_TYPE[key],
        value: key
      }
    })
  },
  {
    name: '作者',
    value: 'authorName',
    type: 'input'
  },
  {
    name: '新闻来源',
    value: 'sources',
    type: 'select',
    data: Object.keys(NEWS_SOURCE).map((key) => {
      return {
        label: NEWS_SOURCE[key],
        value: key
      }
    })
  }
]
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '新闻标题',
    dataIndex: 'title',
    ellipsis: true,
    width: '20%'
  },
  {
    title: '新闻类别',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '作者',
    ellipsis: true,
    dataIndex: 'authorName'
  },
  {
    title: '数据来源',
    dataIndex: 'sources',
    scopedSlots: { customRender: 'sources' }
  },
  {
    title: '创建时间',
    width: 180,
    dataIndex: 'createTime'
  },
  {
    title: '发布时间',
    width: 180,
    dataIndex: 'releaseTime'
  },
  {
    title: '置顶状态',
    dataIndex: 'topStatus',
    scopedSlots: { customRender: 'topStatus' }
  },
  {
    title: '发布状态',
    dataIndex: 'releaseStatus',
    scopedSlots: { customRender: 'releaseStatus' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  data() {
    return {
      searchArr,
      columns,
      totalInfo: {
        totalNum: 0
      },
      loadingState: {
        revoke: false,
        setTop: false,
        cancelTop: false,
        delete: false
      }
    }
  },
  computed: {
    btnVisible() {
      const btnPermission = this.$store.getters.btnPermission
      const codeMap = {
        pa_017_cel_06: 'revoke', // 撤销
        pa_017_top_07: 'top', // 置顶/取消置顶
        pa_017_del_03: 'delete' // 删除
      }
      const result = {
        revoke: false,
        top: false,
        delete: false
      }
      btnPermission.forEach((item) => {
        if (codeMap[item.code]) {
          result[codeMap[item.code]] = true
        }
      })
      return result
    }
  },
  methods: {
    /**
     * 检查是否显示更多按钮，只有当更多里的所有按钮都不显示时，更多按钮才不显示。
     * @param {Object} data {isRevoke: Boolean, isSetTop: Boolean, isCancelTop: Boolean, isDelete: Boolean}
     */
    checkMoreBtn(data) {
      return Object.keys(data)
        .map((key) => data[key])
        .some((item) => !!item)
    },
    /**
     * 检查是否显示对应按钮(撤销、置顶、取消置顶、删除)
     * @returns {Object} {isRevoke: Boolean, isSetTop: Boolean, isCancelTop: Boolean, isDelete: Boolean}
     */
    checkMoreBtnVisible(record) {
      const btnVisible = this.btnVisible
      const isRevoke = btnVisible.revoke && record.releaseStatus == 1
      const isSetTop = btnVisible.top && record.releaseStatus == 1 && record.topStatus != 1
      const isCancelTop = btnVisible.top && record.releaseStatus == 1 && record.topStatus == 1
      const isDelete = btnVisible.delete
      return {
        isRevoke,
        isSetTop,
        isCancelTop,
        isDelete
      }
    },
    /**
     * 分别过滤类别、数据来源、置顶状态、发布状态
     */
    filterLabel(val, key) {
      const keyMap = {
        type: NEWS_TYPE,
        sources: NEWS_SOURCE,
        topStatus: TOP_STATUS,
        releaseStatus: RELEASE_STATUS
      }
      return (keyMap[key] && keyMap[key][val]) || ''
    },
    async handleUpdate(data, actionType) {
      // 若查看的是oa平台则打开外部链接
      if (actionType === 'look' && data.sources === '2') {
        const Res = await getContentById({ id: data.id })
        if (Res?.data?.code === 200) {
          window.open(Res.data.message)
        }
        return
      }
      const commonHandler = () => {
        this.$router.push({
          path: `/partyMasses/partyManage/newsManage/${actionType === 'look' ? 'newsDetail?' : 'update'}`,
          query: {
            pageType: actionType,
            id: data.id || '',
            releaseStatus: data.releaseStatus || '',
            preView: 1
          }
        })
      }
      const actionMap = {
        add: commonHandler,
        publish: commonHandler,
        look: commonHandler,
        revoke: () => {
          this.$confirm({
            content: '请确认是否撤销？',
            onOk: async () => {
              await undoNews({ id: data.id })
              const params = {
                id: data.id,
                releaseStatus: 0
              }
              await updateReleaseStatus(params)
              this.$message.success('撤销成功')
              this.handleSearch(null, false)
            }
          })
        },
        setTop: async () => {
          this.$confirm({
            content: '请确认是否置顶？',
            onOk: async () => {
              try {
                const params = {
                  id: data.id,
                  topStatus: 1
                }
                await updateTopStatus(params)
                this.$message.success('置顶成功')
                this.handleSearch(null, false)
              } catch (e) {
                return Promise.resolve()
              }
            }
          })
        },
        cancelTop: async () => {
          this.$confirm({
            content: '请确认是否取消置顶？',
            onOk: async () => {
              const params = {
                id: data.id,
                topStatus: 0
              }
              await updateTopStatus(params)
              this.$message.success('取消置顶成功')
              this.handleSearch(null, false)
            }
          })
        },
        delete: () => {
          this.$confirm({
            content: '请确认是否删除该数据？',
            onOk: async () => {
              const params = {
                id: data.id
              }
              await deleteData(params)
              this.$message.success('删除成功')
              this.handleSearch(null, false)
            }
          })
        }
      }
      actionMap[actionType] && actionMap[actionType](data)
    },
    async loadData(parameter) {
      const { pageNo, pageSize } = parameter
      const requestParameters = {
        pageNum: pageNo,
        pageSize,
        param: this.queryParam || {}
      }
      // 设置未发布新闻数量
      getNoReleaseNewsNum().then((res) => {
        if (res.code === 200 || res.data.code === 200) {
          this.$store.commit('messageInfo/SET_TONEWSCOUNT', res.data)
        }
      })
      return getList(requestParameters).then((res) => {
        this.totalInfo.totalNum = res.data.total
        return {
          code:200,
          data: res.data.list || [],
          currentPage: res.data.pageNum,
          totalSize: res.data.total
        }
      })
    },
    handleSearch(val, flag) {
      val &&
        (this.queryParam = {
          ...val
        })
      this.refreshTable(flag)
    },
    refreshTable(flag = true) {
      this.$refs.table.refresh(flag)
    }
  }
}
</script>

<style>
</style>